package com.yaorange.jk.web;


import com.opensymphony.xwork2.ActionSupport;
import com.yaorange.jk.entity.User;
import com.yaorange.jk.utils.SysConstant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

public class LoginAction extends ActionSupport {

	private String username;
	private String password;
	private String errorMsg;
	public String login(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		//判断session 是否为空，空则继续登录，否则直接转发到 fmain.jsp
		if(session.getAttribute(SysConstant.CURRENT_USER_INFO)!=null){
			return SUCCESS;
		}
		if (username!=null&&!username.isEmpty()&&password!=null&&!password.isEmpty()){
			try {
				//获取当前用户
				Subject subject = SecurityUtils.getSubject();
				UsernamePasswordToken upt = new UsernamePasswordToken(username,password);
				subject.login(upt);
				//登录成功后。将用户信息放入到Session中；
				User user = (User) subject.getPrincipal();
				session.setAttribute(SysConstant.CURRENT_USER_INFO,user);
			}catch (Exception e){
				errorMsg = "用户名或密码错误！";
				return "login";
			}

		}else{
			return "login";
		}
		return "success";
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
